package yc.star.system.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yc.star.common.domain.AppResult;
import yc.star.common.security.exception.ApplicationException;
import yc.star.system.domain.es.QuestionES;
import yc.star.system.domain.question.Question;
import yc.star.system.domain.question.dto.QuestionAddDTO;
import yc.star.system.domain.question.dto.QuestionEditDTO;
import yc.star.system.domain.question.dto.QuestionQueryDto;
import yc.star.system.domain.question.vo.QuestionDetailVO;
import yc.star.system.domain.question.vo.QuestionVO;
import yc.star.system.elasticsearch.QuestionRepository;
import yc.star.system.manager.QuestionCacheManager;
import yc.star.system.mapper.QuestionMapper;
import yc.star.system.service.IQuestionService;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Override
    public List<QuestionVO> list(QuestionQueryDto questionQueryDto) {
        String excludeIdStr = questionQueryDto.getExcludeIdStr();
        if (StrUtil.isNotEmpty(excludeIdStr)) {
            String[] excludeIdArr = excludeIdStr.split(";");
            Set<Long> excludeIdSet = Arrays.stream(excludeIdArr)
                    .map(Long::valueOf)
                    .collect(Collectors.toSet());
            questionQueryDto.setExcludeIdSet(excludeIdSet);
        }
        PageHelper.startPage(questionQueryDto.getPageNum(),questionQueryDto.getPageSize());
        List<QuestionVO> questionVOS = questionMapper.selectQuestionList(questionQueryDto);
        return questionVOS;
    }

    @Override
    public boolean add(QuestionAddDTO questionAddDTO) {
        List<Question> questions = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .eq(Question::getTitle, questionAddDTO.getTitle()));
        if (CollectionUtil.isNotEmpty(questions)) {
            throw new ApplicationException(AppResult.failed("该题目题库中已存在"));
        }
        Question question = new Question();
        BeanUtil.copyProperties(questionAddDTO,question);
        // 将题目信息插入数据库
        int rows = questionMapper.insert(question);
        if (rows <= 0) {
            return false;
        }
        // 将题目信息插入ES
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(question,questionES);
        questionRepository.save(questionES);
        questionCacheManager.addCache(question.getQuestionId());
        return true;
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            throw new ApplicationException(AppResult.failed("该题目不存在或已被删除"));
        }
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public int edit(QuestionEditDTO questionEditDTO) {
        Question oldQuestion = questionMapper.selectById(questionEditDTO.getQuestionId());
        if (oldQuestion == null) {
            throw new ApplicationException(AppResult.failed("该题目不存在或已被删除"));
        }
        // 预置更新数据
        oldQuestion.setTitle(questionEditDTO.getTitle());
        oldQuestion.setDifficulty(questionEditDTO.getDifficulty());
        oldQuestion.setTimeLimit(questionEditDTO.getTimeLimit());
        oldQuestion.setSpaceLimit(questionEditDTO.getSpaceLimit());
        oldQuestion.setContent(questionEditDTO.getContent());
        oldQuestion.setQuestionCase(questionEditDTO.getQuestionCase());
        oldQuestion.setDefaultCode(questionEditDTO.getDefaultCode());
        oldQuestion.setMainFuc(questionEditDTO.getMainFuc());
        // 将Es中的数据更新
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(oldQuestion,questionES);
        questionRepository.save(questionES);
        // 更新数据到数据库
        return questionMapper.updateById(oldQuestion);
    }

    @Override
    public int delete(Long questionId) {
        Question oldQuestion = questionMapper.selectById(questionId);
        if (oldQuestion == null) {
            throw new ApplicationException(AppResult.failed("该题目不存在或已被删除"));
        }
        // 将Es中的对应的数据删除
        questionRepository.deleteById(questionId);
        // 删除题目id列表中的缓存
        questionCacheManager.deleteCache(questionId);
        int rows = questionMapper.deleteById(questionId);
        return rows;
    }

}